--[[
	service，处理排行榜数据
	每次启动，从redis获取排行榜数据，排行榜保存在内存中
	gate来请求数据，就传给agent

	然后一个接口，定时可以去重建更新排行榜数据
	使用datasheet，只是为了测试一下而已。
]]
local filename = "rank.lua"
local skynet = require "skynet"
local cluster = require "skynet.cluster"

require "skynet.manager"

local json = require "cjson.safe"
json.encode_sparse_array(true,1,1)

local redisdao = require "redisdao"
local filelog = require "filelog"
local timetool = require "timetool"

local routerbase = require "routerbase"

local Rank = routerbase:new()

local rankdata ={}

function Rank.CMD.get_rank()
	return rankdata
end

-- 每次gm启动，从redis里面获取排行榜数据，push 到 gatenode的router
function Rank.CMD.get_rank_from_redis()
    local ranklist = {[2] = "diamondrank",[3] = "coinrank", [4] = "drrank", [5] = "beaterrank", [6] = "shooterrank", [7] = "linkerrank",}
    for ranktype,rankname in pairs(ranklist) do
        local result, result_data = redisdao.query_data(".gmmqredis", "get", rankname)
	    if result_data then
            rankdata[ranktype] = json.decode(result_data)
	    else
		    Rank.CMD.renew_rank(rankname, ranktype, 10, true)
	    end
    end
    --pcall(cluster.send,"gatenode", ".router", "setrank", rankdata)
    
	return true	
end

-- 更新排行榜，或者是webgm来调用，或者就是定时去调用，或者有个crontab，定时写更新命令到redis
-- 最后push 到 gatenode的router
function Rank.CMD.renew_rank(rankname, ranktype, linenum, is_notnotify_gate)
	linenum = linenum or 10
    ranktype = tonumber(ranktype) or 2
	local ranklist = cluster.call("datanode", ".router", "newrank", ranktype, tonumber(linenum))
	if type(ranklist) ~= "table" then
		return false
	elseif next(ranklist) == nil then
		ranklist = cluster.call("datanode", ".router", "newrank", ranktype, tonumber(linenum))
	end
    rankdata[ranktype] = { }
	rankdata[ranktype].ranktime = timetool.get_time()
	for i,v in ipairs(ranklist) do
		ranklist[i]["rankorder"] = i
	end
    rankdata[ranktype].ranktype = ranktype
	rankdata[ranktype].ranklist = ranklist
	redisdao.query_data(".gmmqredis", "set", rankname, json.encode(rankdata[ranktype]))
    if not is_notnotify_gate then
        pcall(cluster.send,"gatenode", ".router", "setrank", rankdata)
    end
	
	return true
end

skynet.start(function ()
	Rank:start()
end)
